package cn.nfwx.tv.util;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import cn.nfwx.tv.callback.ResponseCallback;
import cn.nfwx.tv.callback.ResponseWithFailListener;
import cn.nfwx.tv.conts.Constants;
import cn.nfwx.tv.helper.AccountHelper;
import cn.nfwx.tv.helper.ValueCallback;
import cn.nfwx.tv.manager.UserManager;
import cn.nfwx.tv.vo.ResultErrorVo;

/**
 * Created by zb.liu on 2017/11/16.
 */

public class ToolUtil {

    /***
     * 像素转化
     * @param context
     * @param dpValue
     * @return
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 手机格式
     *
     * @param str
     * @return
     * @throws PatternSyntaxException
     */
    public static boolean isPhoneLegal(String str) throws PatternSyntaxException {
        String regExp = "^((1[0-9][0-9]))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    public static boolean isPassWordLegal(String str) {
        if (TextUtils.isEmpty(str)) {
            return false;
        } else if (str.length() < 6 || str.length() > 15) {
            return false;
        }
        return true;
    }

    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    /***
     * inputStream 转String
     * @param in
     * @return
     * @throws IOException
     */
    public static String inputStream2String(InputStream in) throws IOException {
        StringBuffer out = new StringBuffer();
        InputStreamReader inread = new InputStreamReader(in, "utf-8");
        char[] b = new char[1024];
        for (int n; (n = inread.read(b)) != -1; ) {
            out.append(new String(b, 0, n));
        }
        return out.toString();
    }

    public static void toCheckPhone(final Activity activity, EditText editText, final int type, final ValueCallback<Boolean> valueCallback) {
        toCheckPhone(activity, editText, type, valueCallback, null);
    }

    public static void toCheckPhone(final Activity activity, EditText editText, final int type, final ValueCallback<Boolean> booleanValueCallback, final ValueCallback<String> nickValueCallback) {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (ToolUtil.isPhoneLegal(s.toString())) {
                    if (AccountHelper.getInstance().getLiveStats() == Constants.STATS_P2P) {
                        /**
                         * 校验手机是否注册
                         */
                        UserManager.checkPhone(activity, s.toString(), new ResponseWithFailListener<String>() {
                            @Override
                            public void onResponse(String requestTag, final String response) {
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (response != null) {
                                            if (type == 2) {
                                                Toast.makeText(activity, "该号码已注册", Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    }
                                });

                            }

                            @Override
                            public void onError(String requestTag, Throwable t) {

                            }

                            @Override
                            public void onFinish() {

                            }

                            @Override
                            public void onFail(String requestTag, final String response) {
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            if (!TextUtils.isEmpty(response)) {
                                                Gson gson = new Gson();
                                                ResultErrorVo resultErrorVo = gson.fromJson(response, ResultErrorVo.class);
                                                if (type == 1) {
                                                    Toast.makeText(activity, "该号码未注册", Toast.LENGTH_LONG).show();
                                                }
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }

                                    }
                                });

                            }
                        });
                    } else if (AccountHelper.getInstance().getLiveStats() == Constants.STATS_QPOP) {
                        UserManager.requestIjkCheckPhone(activity, s.toString(), new ResponseCallback<JSONObject>() {
                            @Override
                            public void onSuccess(String requestTag, final JSONObject result) {
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (result.getIntValue("uid") > 0) {
                                            if (type == 2) {
                                                Toast.makeText(activity, "该号码已注册", Toast.LENGTH_LONG).show();
                                            }
                                            if (booleanValueCallback != null) {
                                                booleanValueCallback.onReceiveValue(true);
                                            }
                                            if (nickValueCallback != null) {
                                                String nick = result.getString("nick");
                                                nickValueCallback.onReceiveValue(nick);
                                            }
                                        } else if (result.getIntValue("uid") == 0) {
                                            if (type == 1) {
                                                Toast.makeText(activity, "该号码未注册", Toast.LENGTH_LONG).show();
                                            }
                                            if (booleanValueCallback != null) {
                                                booleanValueCallback.onReceiveValue(false);
                                            }
                                        }
                                    }
                                });
                            }

                            @Override
                            public void onFailure(String requestTag, String message) {

                            }
                        });
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    public static void toCheckPhone(final Activity activity, EditText editText, final int type) {//type：1
        toCheckPhone(activity, editText, type, null);
    }

    public static void toSetEditTextLength(final Activity activity, EditText editText,
                                           int length) {
        editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(length)});
    }

    public static int[] getRes(Context context, int arrayRes) {
        TypedArray typedArray = context.getResources().obtainTypedArray(arrayRes);
        int len = typedArray.length();
        int[] resId = new int[len];
        for (int i = 0; i < len; i++) {
            resId[i] = typedArray.getResourceId(i, -1);
        }
        typedArray.recycle();
        return resId;
    }
}
